<template>
  <div class="right-board">
    <el-tabs v-model="currentTab" class="center-tabs">
      <el-tab-pane label="组件属性" name="field" />
      <el-tab-pane label="表单属性" name="form" />
    </el-tabs>
    <div class="field-box">
      <el-scrollbar class="right-scrollbar">
        <!-- 组件属性 -->
        <el-form v-show="currentTab==='field' && showField" size="small" label-width="90px">
          <el-form-item v-if="activeData?.__config__?.changeTag" label="组件类型">
            <el-select
              v-model="activeData.__config__.tagIcon"
              placeholder="请选择组件类型"
              :style="{width: '100%'}"
              @change="tagChange"
            >
              <el-option-group v-for="group in tagList" :key="group.label" :label="group.label">
                <el-option
                  v-for="item in group.options"
                  :key="item?.__config__?.label"
                  :label="item?.__config__?.label"
                  :value="item?.__config__?.tagIcon"
                >
                  <span> {{ item?.__config__?.label }}</span>
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item v-if="activeData?.__vModel__!==undefined" label="字段名">
            <el-input v-model="activeData.__vModel__" placeholder="请输入字段名（v-model）" />
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.componentName!==undefined" label="组件名">
            {{ activeData?.__config__?.componentName }}
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.label!==undefined" label="标题">
            <el-input v-model="activeData.__config__.label" placeholder="请输入标题" @input="changeRenderKey" />
          </el-form-item>
          <el-form-item v-if="activeData?.placeholder!==undefined" label="占位提示">
            <el-input v-model="activeData.placeholder" placeholder="请输入占位提示" @input="changeRenderKey" />
          </el-form-item>
          <el-form-item v-if="activeData['start-placeholder']!==undefined" label="开始占位">
            <el-input v-model="activeData['start-placeholder']" placeholder="请输入占位提示" />
          </el-form-item>
          <el-form-item v-if="activeData['end-placeholder']!==undefined" label="结束占位">
            <el-input v-model="activeData['end-placeholder']" placeholder="请输入占位提示" />
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.span!==undefined" label="表单栅格">
            <el-slider v-model="activeData.__config__.span" :max="24" :min="1" :marks="{12:''}" @change="spanChange" />
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.layout==='rowFormItem'&&activeData?.gutter!==undefined" label="栅格间隔">
            <el-input-number v-model="activeData.gutter" :min="0" placeholder="栅格间隔" />
          </el-form-item>
<!--          <el-form-item v-if="activeData?.__config__?.display==='rowFormItem'&&activeData?.type!==undefined" label="布局模式">-->
<!--            <el-radio-group v-model="activeData?.type">-->
<!--              <el-radio-button label="default" />-->
<!--              <el-radio-button label="flex" />-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
<!--          <el-form-item v-if="activeData?.justify!==undefined&&activeData?.type==='flex'" label="水平排列">-->
<!--            <el-select v-model="activeData?.justify" placeholder="请选择水平排列" :style="{width: '100%'}">-->
<!--              <el-option-->
<!--                v-for="(item, index) in justifyOptions"-->
<!--                :key="index"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item v-if="activeData?.align!==undefined&&activeData?.type==='flex'" label="垂直排列">-->
<!--            <el-radio-group v-model="activeData?.align">-->
<!--              <el-radio-button label="top" />-->
<!--              <el-radio-button label="middle" />-->
<!--              <el-radio-button label="bottom" />-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
          <el-form-item v-if="activeData?.__config__?.labelWidth!==undefined" label="标签宽度">
            <el-input v-model.number="activeData.__config__.labelWidth" type="number" placeholder="请输入标签宽度" />
          </el-form-item>
          <el-form-item v-if="activeData?.style&&activeData?.style.width!==undefined" label="组件宽度">
            <el-input v-model="activeData.style.width" placeholder="请输入组件宽度" clearable />
          </el-form-item>
          <el-form-item v-if="activeData?.__vModel__!==undefined" label="默认值">
            <el-input
              :model-value="setDefaultValue(activeData?.__config__?.defaultValue)"
              placeholder="请输入默认值"
              @update:modelValue="onDefaultValueInput"
            />
          </el-form-item>
          <el-form-item v-if="activeData?.autosize !== undefined" label="最小行数">
            <el-input-number v-model="activeData.autosize.minRows" :min="1" placeholder="最小行数" />
          </el-form-item>
          <el-form-item v-if="activeData?.autosize !== undefined" label="最大行数">
            <el-input-number v-model="activeData.autosize.maxRows" :min="1" placeholder="最大行数" />
          </el-form-item>
          <el-form-item v-if="activeData?.height!==undefined" label="组件高度">
            <el-input-number v-model="activeData.height" placeholder="高度" @input="changeRenderKey" />
          </el-form-item>
          <el-form-item v-if="activeData.maxlength !== undefined" label="最多输入">
            <el-input v-model="activeData.maxlength" placeholder="请输入字符长度">
              <template slot="append">
                个字符
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="activeData?.type !== undefined && activeData?.__config__?.tag === 'el-button'"
            label="按钮类型"
          >
            <el-select v-model="activeData.type" :style="{ width: '100%' }">
              <el-option label="primary" value="primary" />
              <el-option label="success" value="success" />
              <el-option label="warning" value="warning" />
              <el-option label="danger" value="danger" />
              <el-option label="info" value="info" />
              <el-option label="text" value="text" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="activeData?.__config__?.buttonText !== undefined"
            v-show="'picture-card' !== activeData['list-type']"
            label="按钮文字"
          >
            <el-input v-model="activeData.__config__.buttonText" placeholder="请输入按钮文字" />
          </el-form-item>
          <el-form-item
            v-if="activeData.__config__.tag === 'el-button'"
            label="按钮文字"
          >
            <el-input v-model="activeData.__slot__.default" placeholder="请输入按钮文字" />
          </el-form-item>
          <template v-if="['el-checkbox-group', 'el-radio-group', 'el-select'].indexOf(activeData?.__config__?.tag) > -1">
            <el-divider>选项</el-divider>
            <draggable
              :list="activeData.__slot__.options"
              :animation="340"
              group="selectItem"
              handle=".option-drag"
            >
              <template #item="{element, index}">
                <div :key="index" class="select-item">
                  <div class="select-line-icon option-drag">
                    <el-icon><Operation /></el-icon>
                    <i class="el-icon-s-operation" />
                  </div>
                  <el-input v-model="element.label" placeholder="选项名" size="small" />
                  <el-input
                    placeholder="选项值"
                    size="small"
                    :model-value="element.value"
                    @update:modelValue="setOptionValue('value', element, $event)"
                  />
                  <div class="close-btn select-line-icon" @click="activeData?.__slot__.options.splice(index, 1)">
                    <el-icon color="red"><Remove /></el-icon>
                  </div>
                </div>
              </template>
            </draggable>
            <div style="margin-left: 20px;">
              <el-button
                style="padding-bottom: 0"
                icon="el-icon-circle-plus-outline"
                type="text"
                @click="addSelectItem"
              >
                添加选项
              </el-button>
            </div>
            <el-divider />
          </template>
          <template v-if="['el-table', 'table-query'].includes(activeData?.__config__?.tag)">
            <el-divider>数据列</el-divider>
            <draggable
              v-model="activeData.__slot__.columns"
              :animation="340"
              group="columnItem"
              handle=".option-drag"
            >
              <template #item="{element, index}">
                <div :key="index" class="select-item">
                  <div class="select-line-icon option-drag">
                    <el-icon><Operation/></el-icon>
                  </div>
                  <el-input v-model="element.label" placeholder="列名" size="small" />
                  <el-input
                    placeholder="列字段"
                    size="small"
                    :model-value="element.prop"
                    @update:modelValue="setOptionValue('prop', element, $event)"
                  />
                  <div class="close-btn select-line-icon" @click="activeData?.__slot__.columns.splice(index, 1)">
                    <el-icon><Remove/></el-icon>
                  </div>
                </div>
              </template>
            </draggable>
            <div style="margin-left: 20px;">
              <el-button
                style="padding-bottom: 0"
                icon="el-icon-circle-plus-outline"
                type="text"
                @click="addColumnItem"
              >
                添加字段
              </el-button>
            </div>
            <el-divider />
          </template>

          <el-form-item v-if="activeData?.__config__?.optionType !== undefined" label="选项样式">
            <el-radio-group v-model="activeData.__config__.optionType">
              <el-radio-button label="default">
                默认
              </el-radio-button>
              <el-radio-button label="button">
                按钮
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.showLabel !== undefined
            && activeData?.__config__?.labelWidth !== undefined" label="显示标签"
          >
            <el-switch v-model="activeData.__config__.showLabel" />
          </el-form-item>
          <el-form-item
            v-if="activeData?.__config__?.border !== undefined && activeData?.__config__?.optionType === 'default'"
            label="是否带边框"
          >
            <el-switch v-model="activeData.__config__.border" />
          </el-form-item>
          <el-form-item
            v-if="activeData?.size !== undefined &&
              (activeData?.__config__?.optionType === 'button' ||
                activeData?.__config__?.border ||
                activeData?.__config__?.tag === 'el-color-picker' ||
                activeData?.__config__?.tag === 'el-button')"
            label="组件尺寸"
          >
            <el-radio-group v-model="activeData.size">
              <el-radio-button label="medium">
                中等
              </el-radio-button>
              <el-radio-button label="small">
                较小
              </el-radio-button>
              <el-radio-button label="mini">
                迷你
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="activeData['show-word-limit'] !== undefined" label="输入统计">
            <el-switch v-model="activeData['show-word-limit']" />
          </el-form-item>
          <el-form-item v-if="activeData?.clearable !== undefined" label="能否清空">
            <el-switch v-model="activeData.clearable" />
          </el-form-item>
          <el-form-item v-if="activeData?.readonly !== undefined" label="是否只读">
            <el-switch v-model="activeData.readonly" />
          </el-form-item>
          <el-form-item v-if="activeData?.disabled !== undefined" label="是否禁用">
            <el-switch v-model="activeData.disabled" />
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.tag === 'el-select'" label="能否搜索">
            <el-switch v-model="activeData.filterable" />
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.tag === 'el-select'" label="是否多选">
            <el-switch v-model="activeData.multiple" @change="multipleChange" />
          </el-form-item>
          <el-form-item v-if="activeData?.__config__?.required !== undefined" label="是否必填">
            <el-switch v-model="activeData.__config__.required" />
          </el-form-item>
        </el-form>
        <!-- 表单属性 -->
        <el-form v-show="currentTab === 'form'" size="small" label-width="90px">
          <el-form-item label="表单名">
            <el-input v-model="formConf.formRef" placeholder="请输入表单名（ref）" />
          </el-form-item>
          <el-form-item label="表单模型">
            <el-input v-model="formConf.formModel" placeholder="请输入数据模型" />
          </el-form-item>
          <el-form-item label="校验模型">
            <el-input v-model="formConf.formRules" placeholder="请输入校验模型" />
          </el-form-item>
          <el-form-item label="表单尺寸">
            <el-radio-group v-model="formConf.size">
              <el-radio-button label="medium">
                中等
              </el-radio-button>
              <el-radio-button label="small">
                较小
              </el-radio-button>
              <el-radio-button label="mini">
                迷你
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标签对齐">
            <el-radio-group v-model="formConf.labelPosition">
              <el-radio-button label="left">
                左对齐
              </el-radio-button>
              <el-radio-button label="right">
                右对齐
              </el-radio-button>
              <el-radio-button label="top">
                顶部对齐
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标签宽度">
            <el-input v-model.number="formConf.labelWidth" type="number" placeholder="请输入标签宽度" />
          </el-form-item>
          <el-form-item label="栅格间隔">
            <el-input-number v-model="formConf.gutter" :min="0" placeholder="栅格间隔" />
          </el-form-item>
          <el-form-item label="禁用表单">
            <el-switch v-model="formConf.disabled" />
          </el-form-item>
<!--          <el-form-item label="显示未选中组件边框">-->
<!--            <el-switch v-model="formConf.unFocusedComponentBorder" />-->
<!--          </el-form-item>-->
        </el-form>
      </el-scrollbar>
    </div>
<!--    <treeNode-dialog :visible.sync="dialogVisible" title="添加选项" @commit="addNode" />-->
<!--    <icons-dialog :visible.sync="iconsVisible" :current="activeData[currentIconModel]" @select="setIcon" />-->
  </div>
</template>

<script lang="jsx">
// import TreeNodeDialog from '@/views/index/TreeNodeDialog'
import { isNumberStr } from '@/utils/index'
// import IconsDialog from './IconsDialog'
import {
  inputComponents, actionComponents, pageComponents
} from '@/components/generator/config'
import draggable from "vuedraggable";
import {Operation, Remove} from "@element-plus/icons-vue";

const dateTimeFormat = {
  date: 'yyyy-MM-dd',
  week: 'yyyy 第 WW 周',
  month: 'yyyy-MM',
  year: 'yyyy',
  datetime: 'yyyy-MM-dd HH:mm:ss',
  daterange: 'yyyy-MM-dd',
  monthrange: 'yyyy-MM',
  datetimerange: 'yyyy-MM-dd HH:mm:ss'
}

// 使changeRenderKey在目标组件改变时可用
const needRerenderList = ['tinymce']

export default {
  components: {Operation, Remove, draggable},
  props: ['showField', 'activeData', 'formConf'],
  data() {
    return {
      currentTab: 'field',
      currentNode: null,
      dialogVisible: false,
      iconsVisible: false,
      currentIconModel: null,
      dateTypeOptions: [
        {
          label: '日(date)',
          value: 'date'
        },
        {
          label: '周(week)',
          value: 'week'
        },
        {
          label: '月(month)',
          value: 'month'
        },
        {
          label: '年(year)',
          value: 'year'
        },
        {
          label: '日期时间(datetime)',
          value: 'datetime'
        }
      ],
      dateRangeTypeOptions: [
        {
          label: '日期范围(daterange)',
          value: 'daterange'
        },
        {
          label: '月范围(monthrange)',
          value: 'monthrange'
        },
        {
          label: '日期时间范围(datetimerange)',
          value: 'datetimerange'
        }
      ],
      colorFormatOptions: [
        {
          label: 'hex',
          value: 'hex'
        },
        {
          label: 'rgb',
          value: 'rgb'
        },
        {
          label: 'rgba',
          value: 'rgba'
        },
        {
          label: 'hsv',
          value: 'hsv'
        },
        {
          label: 'hsl',
          value: 'hsl'
        }
      ],
      justifyOptions: [
        {
          label: 'start',
          value: 'start'
        },
        {
          label: 'end',
          value: 'end'
        },
        {
          label: 'center',
          value: 'center'
        },
        {
          label: 'space-around',
          value: 'space-around'
        },
        {
          label: 'space-between',
          value: 'space-between'
        }
      ],
      layoutTreeProps: {
        label(data, node) {
          const config = data.__config__
          return data.componentName || `${config.label}: ${data.__vModel__}`
        }
      }
    }
  },
  computed: {
    tagList() {
      return [
        {
          label: '输入型组件',
          options: inputComponents
        },
        {
          label: '页面型组件',
          options: pageComponents
        }
      ]
    },
    activeTag() {
      return this.activeData?.__config__?.tag
    },
  },
  watch: {
    formConf: {
      handler(val) {
        // saveFormConf(val)
      },
      deep: true
    },
    activeData: {
      handler(val) {
        console.log('data', val)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    addSelectItem() {
      this.activeData?.__slot__.options.push({
        label: '',
        value: ''
      })
    },
    addColumnItem() {
      this.activeData?.__slot__.columns.push({
        label: '',
        prop: ''
      })
    },
    addTreeItem() {
      ++this.idGlobal
      this.dialogVisible = true
      this.currentNode = this.activeData?.options
    },
    renderContent(h, {node, data, store}) {
      return (
        <div class="custom-tree-node">
          <span>{node.label}</span>
          <span class="node-operation">
            <i on-click={() => this.append(data)}
               class="el-icon-plus"
               title="添加"
            ></i>
            <i on-click={() => this.remove(node, data)}
               class="el-icon-delete"
               title="删除"
            ></i>
          </span>
        </div>
      )
    },
    append(data) {
      if (!data.children) {
        data.children = []
      }
      this.dialogVisible = true
      this.currentNode = data.children
    },
    remove(node, data) {
      this.activeData.__config__.defaultValue = [] // 避免删除时报错
      const {parent} = node
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },
    addNode(data) {
      this.currentNode.push(data)
    },
    setOptionValue(key, item, val) {
      item[key] = isNumberStr(val) ? +val : val
    },
    setDefaultValue(val) {
      if (Array.isArray(val)) {
        return val.join(',')
      }
      // if (['string', 'number'].indexOf(typeof val) > -1) {
      //   return val
      // }
      if (typeof val === 'boolean') {
        return `${val}`
      }
      return val
    },
    onDefaultValueInput(str) {
      if (Array.isArray(this.activeData?.__config__?.defaultValue)) {
        // 数组
        this.activeData.__config__.defaultValue = str.split(',').map(val => (isNumberStr(val) ? +val : val))
      } else if (['true', 'false'].indexOf(str) > -1) {
        // 布尔
        this.activeData.__config__.defaultValue = JSON.parse(str)
      } else {
        // 字符串和数字
        this.activeData.__config__.defaultValue = isNumberStr(str) ? +str : str
      }
    },
    onSwitchValueInput(val, name) {
      if (['true', 'false'].indexOf(val) > -1) {
        this.activeData.name = JSON.parse(val)
      } else {
        this.activeData.name = isNumberStr(val) ? +val : val
      }
    },
    setTimeValue(val, type) {
      const valueFormat = type === 'week' ? dateTimeFormat.date : val
      this.activeData.__config__.defaultValue = null
      this.activeData['value-format'] = valueFormat
      this.activeData.format = val
    },
    spanChange(val) {
      this.formConf.span = val
    },
    multipleChange(val) {
      this.activeData.__config__.defaultValue = val ? [] : ''
    },
    dateTypeChange(val) {
      this.setTimeValue(dateTimeFormat[val], val)
    },
    rangeChange(val) {
      this.activeData.__config__.defaultValue = val ? [this.activeData?.min, this.activeData?.max] : this.activeData?.min
    },
    rateTextChange(val) {
      if (val) this.activeData['show-score'] = false
    },
    rateScoreChange(val) {
      if (val) this.activeData['show-text'] = false
    },
    colorFormatChange(val) {
      this.activeData.__config__.defaultValue = null
      this.activeData['show-alpha'] = val.indexOf('a') > -1
      this.activeData.__config__.renderKey = +new Date() // 更新renderKey,重新渲染该组件
    },
    openIconsDialog(model) {
      this.iconsVisible = true
      this.currentIconModel = model
    },
    setIcon(val) {
      this.activeData[this.currentIconModel] = val
    },
    tagChange(tagIcon) {
      let target = inputComponents.find(item => item?.__config__?.tagIcon === tagIcon)
      if (!target) target = selectComponents.find(item => item?.__config__?.tagIcon === tagIcon)
      this.$emit('tag-change', target)
    },
    changeRenderKey() {
      if (needRerenderList.includes(this.activeData?.__config__?.tag)) {
        this.activeData.__config__.renderKey = +new Date()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.right-board {
  width: 100%;
  height: 100%;
  right: 0;
  top: 0;
  padding-top: 3px;

  .field-box {
    position: relative;
    height: calc(100% - 40px);
    box-sizing: border-box;
    overflow: auto;
  }

  .el-scrollbar {
    height: 100%;
  }
}

.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;

  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }

  & .el-input + .el-input {
    margin-left: 4px;
  }
}

.select-item + .select-item {
  margin-top: 4px;
}

.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}

.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}

.option-drag {
  cursor: move;
}

.time-range {
  .el-date-editor {
    width: 227px;
  }

  :deep(.el-icon-time) {
    display: none;
  }
}

.document-link {
  position: absolute;
  display: block;
  width: 26px;
  height: 26px;
  top: 0;
  left: 0;
  cursor: pointer;
  background: #409eff;
  z-index: 1;
  border-radius: 0 0 6px 0;
  text-align: center;
  line-height: 26px;
  color: #fff;
  font-size: 18px;
}

.node-label {
  font-size: 14px;
}

.node-icon {
  color: #bebfc3;
}
</style>
